import { Message } from 'element-ui';
import axios from 'axios';
import website from "./config";
// import { getToken, getUuid } from "./auth";
import { getToken } from "./auth";
import {
    Base64
} from 'js-base64';

const request = axios.create({
    timeout: 30000,
    // withCredentials: true,
    validateStatus: (status) => {
        return status >= 200 && status <= 500;
    },
});
//http request拦截
request.interceptors.request.use(
    async (config) => {
        config.headers["Authorization"] = `Basic ${Base64.encode(
            `${website.clientId}:${website.clientSecret}`
        )}`;
        // config.headers["Blade-RequestId"] = getUuid();
        //让每个请求携带token
        config.headers[website.tokenHeader] = "bearer " + getToken(config.headers.tokenType || 'plat-token');
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
//http response 拦截
request.interceptors.response.use(
    (res) => {
        //获取状态码
        const status = res.data.code || res.status;
        const message = res.data.msg || res.data.error_description || "未知错误";

        // 如果请求为非200否者默认统一处理
        if (status !== 200) {
            const hideErrorMsg = res.config.params && res.config.params.hideErrorMsg;
            if (hideErrorMsg !== true) {
                Message({
                    message: message,
                    type: "error",
                });
            }
            return Promise.reject(res.data);
        }
        return res;
    },
    (error) => {
        return Promise.reject(new Error(error));
    }
);

export default request;
